package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrOctetString;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class SymmetrySecurity extends AxdrType {
    private ByteBuffer dataCode = null;
    private AxdrOctetString p1 = null;
    private AxdrOctetString s1 = null;

    public void setDataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(AxdrOctetString p1, AxdrOctetString s1) {
        this.p1 = p1;
        this.s1 = s1;
    }

    public void setP1(AxdrOctetString p1) {
        this.p1 = p1;
    }

    public void setS1(AxdrOctetString s1) {
        this.s1 = s1;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.p1 = new AxdrOctetString();
        codeLength += this.p1.decode(input);
        this.s1 = new AxdrOctetString();
        codeLength += this.s1.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            codeLength = this.dataCode.remaining();
            while (this.dataCode.hasRemaining()) {
                output.write(this.dataCode.get());
            }
        } else {
            if (this.p1 != null && this.s1 != null) {
                codeLength += this.s1.encode(output);
                codeLength += this.p1.encode(output);
            } else {
                throw new IllegalArgumentException("p1 or s1 is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.getArray());
    }

    @Override
    public String toString() {
        if (this.p1 != null && this.s1 != null) {
            return "sequence: {" + "p1: " + this.p1 + ", s1: " + this.s1 + "}";
        } else {
            return "p1 or s1 is null";
        }
    }
}



